var sysParam = {
    baseUrl: "/device",
    entity: "padDevice",
    tableId: "padDeviceTable",
    toolbarId: "toolbar",
    currentItem: {}

};
sysParam.columns = function () {
    return [
        {
            field: 'selectItem',
            radio: true
        },{
            title: '序号',
            formatter: function (value, row, index) {
                return index+1;
            }
        }, {
            field: 'deviceId',
            title: '设备号'
        }, {
            field: 'expireDate',
            title: '到期时间'
        }, {
            field: 'createUser',
            title: '创建人'
        }, {
            field: 'createDate',
            title: '创建时间'
        },{
            field: 'updateUser',
            title: '修改人'
        }, {
            field: 'updateDate',
            title: '修改时间'
        },{
            field: 'isValid',
            title: '是否有效',
            formatter: function (value, row, index) {
                var result=''
                if(value=='T'){
                    result='是';
                }else{
                    result='否';
                }
                return  result;
            }
        }];
};
//得到查询的参数
sysParam.queryParams = function (params) {
    if (!params)
        return {
            deviceId:$("#deviceId").val(),
            createUser:$("#createUser").val()
        };
    var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        limit: params.limit, //页面大小
        page: params.offset/params.limit+1, //页码
        deviceId:$("#deviceId").val(),
        createUser:$("#createUser").val()
    };
    return temp;
};
sysParam.responseHandler = function(response){
    if(response.code =='200'){
        return response.data;
    }
    return false;
};
sysParam.init = function () {
    sysParam.table = $('#' + sysParam.tableId).bootstrapTable({
        url: sysParam.baseUrl+'/list', //请求后台的URL（*）
        method: 'get', //请求方式（*）
        toolbar: '#' + sysParam.toolbarId, //工具按钮用哪个容器
        cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true, //是否显示分页（*）
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 10, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        showColumns: false, //是否显示所有的列
        showRefresh: true, //是否显示刷新按钮
        clickToSelect: true,
        sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        singleSelect:true,
        striped:true,
        queryParams: sysParam.queryParams,//传递参数（*）
        responseHandler:sysParam.responseHandler,
        columns: sysParam.columns()
    });
};
sysParam.select = function (layerTips) {
    var rows = sysParam.table.bootstrapTable('getSelections');
    if (rows.length == 1) {
        sysParam.currentItem = rows[0];
        return true;
    } else {
        layerTips.msg("请选中一行");
        return false;
    }
};
sysParam.refresh = function () {
    sysParam.table.bootstrapTable('refresh', sysParam.queryParams());
};


layui.use(['form', 'layedit', 'laydate', 'element'], function () {
    sysParam.init();
    var editIndex;
    //var layerTips = parent.layer === undefined ? layui.layer : parent.layer, //获取父窗口的layer对象
    var layerTips = layui.layer,
    layer = layui.layer, //获取当前窗口的layer对象
        form = layui.form,
        layedit = layui.layedit,
        laydate = layui.laydate;
    var addBoxIndex = -1;

    form.render();

    //初始化页面上面的按钮事件
    $('#btn_query').on('click', function () {
        sysParam.table.bootstrapTable('refresh', sysParam.queryParams());
    });

    $('#btn_add').on('click', function () {
        //var corpCd=sysParam.corpCd;
        //本表单通过ajax加载 --以模板的形式，当然你也可以直接写在页面上读取
        $.get(sysParam.entity + '/edit', null, function (form) {
            addBoxIndex = layer.open({
                type: 1,
                title: '添加设备',
                content: form,
                btn: ['保存', '取消'],
                shade: false,
                offset: ['20px', '20%'],
                area: ['600px', '400px'],
                maxmin: true,
                yes: function (index) {
                    layedit.sync(editIndex);
                    //触发表单的提交事件
                    $('form.layui-form').find('button[lay-filter=edit]').click();
                },
                full: function (elem) {
                    var win = window.top === window.self ? window : parent.window;
                    $(win).on('resize', function () {
                        var $this = $(this);
                        elem.width($this.width()).height($this.height()).css({
                            top: 0,
                            left: 0
                        });
                        elem.children('div.layui-layer-content').height($this.height() - 95);
                    });
                },
                success: function (layero, index) {
                    $("#expireDate").datetimepicker({
                        format:"yyyy-mm-dd hh:ii:ss",
                        language:'zh',
                        autoclose:true
                    });
                    var form = layui.form;
                    var json={
                        "isValid":"YesNo",

                    }
                    selectOnload({
                        "json" : json,
                        "isDefault" : false,
                        "func":form.render,//渲染表单
                        "length" : 1,
                    });
                    form.on('submit(edit)', function (data) {
                        $.ajax({
                            url: sysParam.baseUrl+"/add",
                            type: 'post',
                            data: JSON.stringify(data.field),
                            dataType: "json",
                            contentType:"application/json",
                            success: function (data) {
                                if(data.code=='200'){
                                    layerTips.msg('添加成功');
                                    layerTips.close(index);
                                    sysParam.refresh();
                                }else{
                                    layerTips.msg(data.message);
                                    layerTips.close(index);
                                }
                            }

                        });
                        //这里可以写ajax方法提交表单
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                },
                end: function () {
                    addBoxIndex = -1;
                }
            });
        });
    });
    $('#btn_edit').on('click', function () {
        if (sysParam.select(layerTips)) {
            var result= sysParam.currentItem;
                $.get(sysParam.entity + '/edit', null, function (form) {
                    layer.open({
                        type: 1,
                        title: '编辑设备',
                        content: form,
                        btn: ['保存', '取消'],
                        shade: false,
                        offset: ['20px', '20%'],
                        area: ['600px', '400px'],
                        maxmin: true,
                        yes: function (index) {
                            layedit.sync(editIndex);
                            //触发表单的提交事件
                            $('form.layui-form').find('button[lay-filter=edit]').click();
                        },
                        full: function (elem) {
                            var win = window.top === window.self ? window : parent.window;
                            $(win).on('resize', function () {
                                var $this = $(this);
                                elem.width($this.width()).height($this.height()).css({
                                    top: 0,
                                    left: 0
                                });
                                elem.children('div.layui-layer-content').height($this.height() - 95);
                            });
                        },
                        success: function (layero, index) {
                            var form = layui.form;

                            $("#expireDate").datetimepicker({
                                format:"yyyy-mm-dd hh:ii:ss",
                                language:'zh',
                                autoclose:true
                            });
                            setFromValues(layero, result);//表单赋值
                            layero.find("input[name=deviceId]").attr("readOnly",true);
                            
                            var formRender=function(){
                            	layero.find("select[name='isValid']").val(result.isValid);
                            	form.render();
                            };
                            var json={
                                "isValid":"YesNo",
                            }
                            selectOnload({
                                "json" : json,
                                "isDefault" : false,
                                "func":formRender,//渲染表单
                                "length" : 1,
                            });
                            form.on('submit(edit)', function (data) {
                                $.ajax({
                                    url: sysParam.baseUrl+'/edit',
                                    type: 'put',
                                    data: JSON.stringify(data.field),
                                    contentType:"application/json",
                                    dataType: "json",
                                    success: function (data) {
                                        if(data.code=='200'){
                                            layerTips.msg('更新成功');
                                            layerTips.close(index);
                                            sysParam.refresh();
                                        }else {
                                            layerTips.msg(data.message);
                                            layerTips.close(index);
                                        }
                                    }

                                });
                                //这里可以写ajax方法提交表单
                                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                            });
                        }
                    });
                });
        }
    });
    $('#btn_del').on('click', function () {
        if (sysParam.select(layerTips)) {
            layer.confirm('确定删除数据吗？', null, function (index) {
                $.ajax({
                    url: sysParam.baseUrl,
                    type: "DELETE",
                    contentType:"application/json",
                    data: JSON.stringify(sysParam.currentItem),
                    success: function (data) {
                        if (data.code == '200') {
                            layerTips.msg("移除成功！");
                            sysParam.refresh();
                        } else {
                            layerTips.msg(data.message);
                        }
                    }
                });
                layer.close(index);
            });
        }
    });

});


